package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 类描述：
 */
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFLavorMapper;
    @Autowired
    private SetmealDishMapper setMealDishMapper;

    /**
     * 新增菜品（同时新增口味）
     * @param dishDTO
     */
    @Override
    public void save(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
//        dish.setCreateTime(LocalDateTime.now());
//        dish.setUpdateTime(LocalDateTime.now());
//        dish.setCreateUser(BaseContext.getCurrentId());
//        dish.setUpdateUser(BaseContext.getCurrentId());
        dish.setStatus(StatusConstant.ENABLE);
        dishMapper.save(dish);

        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors == null || flavors.size() == 0) {
            return;
        }
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
            //dishFLavorMapper.saveFlavor(flavor);
        }
        dishFLavorMapper.saveFlavors(flavors);
    }

    /**
     * 菜品分页条件查询
     * @param dto
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<DishVO> dishes = dishMapper.page(dto.getName(), dto.getCategoryId(), dto.getStatus());
        PageResult pageResult = new PageResult(dishes.getTotal(), dishes.getResult());
        return pageResult;
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Transactional
    @Override
    public void delete(List<Long> ids) {
        //如果菜品是在售状态，不能删除
        for (Long id : ids) {
            if (dishMapper.status(id) == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //如果菜品被套餐关联，不能删除
        for (Long id : ids) {
            if (setMealDishMapper.countByDishId(id) != 0) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        }
        //删除菜品，同时删除菜品的口味数据
        for (Long id : ids) {
            dishMapper.delete(id);
            dishFLavorMapper.deleteByDishId(id);
        }
    }

    /**
     * 根据菜品id查询菜品及其口味
     * @param id
     * @return
     */
    @Override
    public DishVO getDishById(Long id) {
        Dish dish = dishMapper.getDishById(id);
        List<DishFlavor> dishFlavors = dishFLavorMapper.getFlavorsByDishId(id);

        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);

        dishVO.setFlavors(dishFlavors);
        dishVO.setCategoryName(dishMapper.getCategoryNameById(id));

        return dishVO;
    }

    /**
     * 修改菜品及其口味
     * @param dishDTO
     */
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
//        dish.setUpdateTime(LocalDateTime.now());
//        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.update(dish);

        dishFLavorMapper.deleteByDishId(dishDTO.getId());

        List<DishFlavor> flavors = dishDTO.getFlavors();

        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishDTO.getId());
            }
            dishFLavorMapper.saveFlavors(flavors);
        }
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Integer categoryId) {
        List<Dish> dishes = dishMapper.listById(categoryId);
        return dishes;
    }

    /**
     * 菜品的启售停售
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder().id(id).status(status).build();
        dishMapper.update(dish);
    }

    /**
     * 根据分类ID查询菜品及其口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {

        //从数据库dish表里查询出所有菜品
        List<Dish> dishList = dishMapper.list(dish);

        //遍历从数据库dish表里查询出的所有的菜品集合，拿到每一个菜品
        // 再查询出该菜品的口味（集合），将每个dish和对应的口味信息dishflavor封装到dishVO对象中
        // 最后将dishVO对象添加到dishVOList集合中
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFLavorMapper.getFlavorsByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        //给前端前端返回集合（包含每个菜品和其对应的口味）
        return dishVOList;
    }
}
